package com.foreknow.controller;

import com.foreknow.model.UserEntity;
import com.foreknow.repository.UserRespository;
import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BIConversion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class MainController {

  @Autowired
  private UserRespository userRespository;

  @RequestMapping(value = "/index",method = RequestMethod.GET)
  public String index() {

    return "index";
  }

  //查询所有用户信息列表
  @RequestMapping(value = "/admin/users",method = RequestMethod.GET)
  public String getUsers(ModelMap modelMap) {
    //调用持久层的方法查询所有用户的信息
    List<UserEntity> userList = userRespository.findAll();
    //将查询到的userList保存到ModelMap中
    modelMap.addAttribute("userList",userList);
    return "admin/users";
  }

  //跳转到addUser.jsp
  @RequestMapping(value = "/admin/users/add",method = RequestMethod.GET)
  public String addUser(){
    return "admin/addUser";
  }


  //添加用户信息
  @RequestMapping(value = "/admin/users/addP",method = RequestMethod.POST)
  public String addUserPost(@ModelAttribute("user") UserEntity userEntity){
    //调用持久层的方法
    userRespository.saveAndFlush(userEntity);
    return "redirect:/admin/users";
  }

  //根据id删除用户的信息
  //restful风格：就是一种设计的风格（设计原则或约束条件），而不是标准
  //每一个URI代表一种资源
  //客户端和服务器之间，传递这种资源的某种表现形式
  //客户端通过四个http动作对服务器的资源进行操作
  //Get(Select)从服务器取出资源
  //Post(Create) 在服务器端创建资源
  //Put(update) 在服务器端更新资源
  //Delete（delete）从服务器删除资源

  @RequestMapping(value = "/admin/users/delete/{id}",method = RequestMethod.GET)
  public String deleteUser(@PathVariable("id") Integer userId){
    userRespository.delete(userId);
    userRespository.flush();
    return "redirect:/admin/users";
  }

  //根据id查询用户的信息
    @RequestMapping(value = "/admin/users/update/{id}",method = RequestMethod.GET)
    public String updateUser(@PathVariable("id") Integer userId,ModelMap modelMap){
      UserEntity userEntity = userRespository.findOne(userId);
      modelMap.addAttribute("user",userEntity);
      return "admin/updateUser";
  }

  //更新用户的信息


}
